package com.orange.wwwapi.security.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.orange.core.pojo.entity.user.User;
import com.orange.core.pojo.enums.EStatus;
import com.orange.core.security.detail.UserDetail;
import com.orange.core.service.user.UserService;
import com.orange.core.util.TokenUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

@RequiredArgsConstructor
@Service
public class WxUserDetailService implements UserDetailsService {

    private final UserService userService;

    @Override
    public UserDetails loadUserByUsername(String openId) throws UsernameNotFoundException {
        User user = userService.getOne(new LambdaQueryWrapper<User>().eq(User::getWxOpenId, openId));
        if (user == null) {
            return null;
        }
        return new UserDetail(user.getId(), user.getNickname(), user.getStatus() == EStatus.NORMAL.getValue())
                .setUser(user).setToken(TokenUtil.newToken());
    }
}
